package com.min.netty.http.handler;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MinHttpServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(MinHttpServerHandler.class);

    private void send(String content, ChannelHandlerContext ctx,
                      HttpResponseStatus status){
        FullHttpResponse response =
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,status,
                        Unpooled.copiedBuffer(content,CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,
                "text/plain;charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.debug("HTTP 连接，客户端地址：{}", ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.debug("HTTP 断开");
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            //接收到完成的http请求
            FullHttpRequest httpRequest = (FullHttpRequest)msg;
            try{
                String path = httpRequest.uri();
                String body = httpRequest.content().toString(CharsetUtil.UTF_8);
                HttpMethod method = httpRequest.method();
                if(!"/test".equalsIgnoreCase(path)){
                    send("非法请求："+path, ctx, HttpResponseStatus.BAD_REQUEST);
                    return;
                }

                //处理http GET请求
                if(HttpMethod.GET.equals(method)){
                    System.out.println("body:"+body);
                    send("this is GET request",ctx,HttpResponseStatus.OK);
                }

                //处理http POST请求
                if(HttpMethod.POST.equals(method)){
                    System.out.println("body:"+body);
                    send("this is POST request",ctx,HttpResponseStatus.OK);
                }

            }catch(Exception e){
                System.out.println("处理请求失败!");
                e.printStackTrace();
            }finally{
                httpRequest.release();
            }
        }
    }
}
